package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.dao.CollectionDao;
import com.xxx.dao.ProductDao;
import com.xxx.pojo.Collection;
import com.xxx.pojo.Product;
import com.xxx.service.CollectionService;
import com.xxx.service.ex.DeleteException;
import com.xxx.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CollectionServiceImpl implements CollectionService {
    private Integer PAGE_SIZE=5;
    @Autowired
    private CollectionDao collectionDao;

    //获取用户所有收藏功能

    @Override
    public IPage getPageCollection(Integer currentPage,Integer uid) {

        IPage<Collection> page=new Page<>(currentPage,PAGE_SIZE);
        LambdaQueryWrapper<Collection> wrapper=new LambdaQueryWrapper();
        wrapper.eq(Collection::getUid,uid).orderByDesc(Collection::getCreatedTime);
        IPage<Collection> collectionIPage = collectionDao.selectPage(page, wrapper);
        return collectionIPage;
    }

    //通过pid 获取 title image price添加收藏
    @Autowired
    private ProductDao productDao;
    @Override
    public void addCollection(Integer pid, Integer uid, String username) {
        Product product = productDao.selectById(pid);
        Collection collection=new Collection();
        collection.setUid(uid);
        collection.setPid(pid);
        collection.setTitle(product.getTitle());
        collection.setImage(product.getImage());
        collection.setPrice(product.getPrice());
        collection.setModifiedUser(username);
        collection.setModifiedTime(new Date());
        collection.setCreatedUser(username);
        collection.setCreatedTime(new Date());
        int row = collectionDao.insert(collection);
        if(row!=1){
            throw new InsertException("(添加收藏操作时)插入数据时产生未知异常");
        }
    }

    //通过id 移除收藏功能
    @Override
    public void removeCollection(Integer id) {
        int row = collectionDao.deleteById(id);
        if(row!=1){
            throw new DeleteException("删除数据时产生未知异常");
        }
    }

}
